package com.ruoyi.quartz.task;

import com.github.tusharepro.core.TushareProService;
import com.github.tusharepro.core.entity.TradeCalEntity;
import com.github.tusharepro.core.http.Request;
import com.ruoyi.quartz.util.TushareUtil;
import com.ruoyi.stock.domain.StockTradeDate;
import com.ruoyi.stock.service.IStockTradeDateService;
import java.io.IOException;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.stream.Collectors;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.stereotype.Component;

/** 股票交易日信息同步 */
@Component("stockTradeDateTask")
@Slf4j
public class StockTradeDateTask {

  @Autowired private IStockTradeDateService stockTradeDateService;

  DateTimeFormatter yyyyMMdd = DateTimeFormatter.ofPattern("yyyyMMdd");

  @Autowired private MongoTemplate mongoTemplate;

  private static final String COLLECTION_NAME = "stockBasic";

  public void run() throws IOException {
    stockTradeDateService.insertBatch(
        tradeCalList().stream()
            .map(
                model ->
                    StockTradeDate.builder()
                        .calDate(yyyyMMdd.format(model.getCalDate()))
                        .isOpen(String.valueOf(model.getIsOpen()))
                        .pretradeDate(model.getPretradeDate())
                        .build())
            .collect(Collectors.toList()));
  }

  /** 股票列表接口 */
  private static List<TradeCalEntity> tradeCalList() throws IOException {
    return TushareProService.tradeCal(
        new Request<TradeCalEntity>(TushareUtil.getBuilder().copy().build()) {}.allFields()
            .param(TradeCalEntity.Params.end_date.value("20250101"))
            .param(TradeCalEntity.Params.start_date.value("20000101")));
  }
}
